class newXhr {
    constructor(beforeHooks={}, afterHooks={}) {
        this.beforeHooks = beforeHooks
        this.afterHooks = afterHooks
        this.XHR = window.XMLHttpRequest
        this.init()
    }
    init(){
        let _this = this
        window.XMLHttpRequest = function (){
            this._xhr = new _this.XHR()
            _this.overWrite(this)
        }
    }

    overWrite(proxyXHR){
        for(let key in proxyXHR){
            if(typeof proxyXHR[key]  === 'function'){
                this.overWriteFunction(key,proxyXHR)
                continue;
            }
            this.overwriteAttributes(key, proxyXHR)
        }
    }

    overWriteFunction(key,proxyXHR){
        let beforeHooks = this.beforeHooks
        let afterHooks = this.afterHooks
        proxyXHR[key] = (...args) =>{
            if(beforeHooks[key]){ // beforeHooks钩子
                // 直接call， 改变this指向， 并且参数是单个的
                beforeHooks[key].call(args)
            }
            // 本来的输出结果
            const res = proxyXHR._xhr.call(proxyXHR._xhr,args)

            // afterHooks钩子, && 可以节省一个if判断， 这里的参数是res
            afterHooks[key] && afterHooks[key].call(proxyXHR._xhr, res)

            // 最后输出一下本来执行的结果
            return res;
        }
    }
    overwriteAttributes(key, proxyXHR){
        Object.defineProperties(proxyXHR, this.setPropertyDescriptor(key, proxyXHR))
    }

    setPropertyDescriptor(key, proxyXHR){

    }
}
